from fastapi import APIRouter
from starlette import status
from starlette.requests import Request
from starlette.responses import JSONResponse, Response

req_res_router = APIRouter(prefix="/request-response", tags=["Request Response对象"])


@req_res_router.get("/response")
async def get_response() -> JSONResponse:
    """
    使用Response 返回内容
    :return:
    """
    return JSONResponse(content={"message": "response"},
                        status_code=status.HTTP_200_OK,
                        media_type="application/json",
                        headers={"X-abc": "custom response header"})


@req_res_router.get("/request")
async def request(req: Request):
    """
        request 对象
    :param req:
    :return:
    """
    return {"message": "request",
            "method": req.method,
            "url": req.url,
            "base_url": req.base_url,
            "client_host": req.client.host}


@req_res_router.get("/responsecookie")
async def response_cookie(response: Response):
    """
    使用Response 返回内容
    :return:
    """
    response.set_cookie(key="cookie_key", value="cookie_value", httponly=True, max_age=3600, secure=True)  # 添加cookie
    return {"message": "response_cookie", }
